'''
Created on Nov 5, 2010

@author: jtk
'''

# Adjust the ladder to account for the match winner and loser.
def adjustLadder(ladder, winner, loser):
    if winner not in ladder:
        ladder.append(winner)
    if loser not in ladder:
        ladder.append(loser)
    wIndex = ladder.index(winner)
    lIndex = ladder.index(loser)

    # If loser is higher up the ladder, then swap their positions
    if lIndex < wIndex:
        (ladder[wIndex], ladder[lIndex]) = (ladder[lIndex], ladder[wIndex])

def removeBenchedPlayers(db, ladder):
    competitors = db(db.competitor.status == 'benched').select(db.competitor.ALL)
    for competitor in competitors:
        c = (competitor.name_user, competitor.name_player)
        if c in ladder:
            ladder.remove(c)
    return ladder
        
def buildLadder(db):
    ladder = []
    matches = db().select(db.match.ALL)
    for match in matches:
        # skip partially completed match
        if match.winner_color == None:
            continue
        winner = (match.winner.name_user, match.winner.name_player)
        loser = (match.loser.name_user, match.loser.name_player)
        adjustLadder(ladder, winner, loser)
    
    ladder = removeBenchedPlayers(db, ladder)
    return ladder

def countWinsLosses(matches):
    wins = {}
    losses = {}
    for match in matches:
        if match.winner_color == None:  # skip partially completed match
            continue
        winner = (match.winner.name_user, match.winner.name_player)
        wins[winner] = wins.setdefault(winner, 0) + 1
        loser = (match.loser.name_user, match.loser.name_player)
        losses[loser] = losses.setdefault(loser, 0) + 1
    return (wins, losses)

def getLadderWinsLosses(db):
    matches = db().select(db.match.ALL, orderby=db.match.id)
    ladder = buildLadder(db)
    (wins, losses) = countWinsLosses(matches)

    for i in xrange(len(ladder)):
        userid = ladder[i][0]
        player = ladder[i][1]
        cWins = wins.setdefault((userid, player), 0)
        cLosses = losses.setdefault((userid, player), 0)
        ladder[i] = (userid, player, cWins, cLosses)
    
    return ladder
